#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re

class CSS():
    """css output_file.css file1.css [file2.css ... fileN.css]"""
    def __init__(self, files):
        self.output = files[0]
        self.files = files[1:]
        self.content = {}
        self.elements = []
        self.classes = []
        self.ids = []

        self.__readfiles()
    
    def __readfiles(self):
        for file_name in self.files:
            f = open(file_name, "r")
            self.__analyse("".join(f.readlines()))
            f.close()
    
    def __analyse(self, content):
        content = re.sub(r"\n", '', content)
        content = re.sub(r"\t", '', content)
        content = re.sub(r"/\*.*?\*/", '', content)
        for keys, items in re.findall(r"(.*?){(.*?)}", content):
            self.__organize_keys(keys, items)
        self.__makeoutput()
    
    def __organize_keys(self, keys, items):
        _items = []
        items = [item for item in items.split(';') if item != '']
        for item in items:
            split_items = item.split(':')
            try: 
                _items.append("%s: %s" % \
                              (split_items[0].strip(), \
                               split_items[1].strip()))
            except:
                pass
        #TODO:
        #сделать сортировку несависимую от регистра
        items = sorted(_items, key=str.lower) 
        
        for key in [key.strip() for key in keys.split(',') if key.strip() != '']:
            item = {'key': key, 'items': items}
            if key[0] == '.':
                self.classes.append(item)
            elif key[0] == '#':
                self.ids.append(item)
            else:
                self.elements.append(item)
    
    def __makeoutput(self):
        f = open(self.output, "w")
        self.elements.sort(key=lambda v: v['key'].lower())
        self.classes.sort(key=lambda v: v['key'].lower())
        self.ids.sort(key=lambda v: v['key'].lower())
        
        f.write("/**\n@summary:\n@author:\n*/\n\n\n")
        for el in [self.elements, self.classes, self.ids]:
            for c in el:
                f.write("%s {\n" % c['key'].strip())
                for item in c['items']:
                    f.write("\t%s;\n" % item.strip())
                f.write("}\n\n")

    
if __name__ == '__main__':
    import sys
    if len(sys.argv) > 2:
        CSS(sys.argv[1:])
    else:
        print CSS.__doc__
